package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.Properties;

/**
 * @see com.alibaba.cloud.sentinel.datasource.RuleType
 */
@Configuration(proxyBeanMethods = false)
public class NacosConfig {
    public static final String FLOW_DATA_ID_POSTFIX = "-flow";
    public static final String DEGRADE_DATA_ID_POSTFIX = "-degrade";
    public static final String PARAM_FLOW_DATA_ID_POSTFIX = "-param-flow";
    public static final String SYSTEM_DATA_ID_POSTFIX = "-system";
    public static final String AUTHORITY_DATA_ID_POSTFIX = "-authority";
    public static final String GW_FLOW_DATA_ID_POSTFIX = "-gw-flow";
    public static final String GW_API_GROUP_DATA_ID_POSTFIX = "-gw-api-group";
    public static final String CLUSTER_MAP_DATA_ID_POSTFIX = "-cluster-map";
    /**
     * cc for `cluster-client`
     */
    public static final String CLIENT_CONFIG_DATA_ID_POSTFIX = "-cc-config";
    /**
     * cs for `cluster-server`
     */
    public static final String SERVER_TRANSPORT_CONFIG_DATA_ID_POSTFIX = "-cs-transport-config";
    public static final String SERVER_FLOW_CONFIG_DATA_ID_POSTFIX = "-cs-flow-config";
    public static final String SERVER_NAMESPACE_SET_DATA_ID_POSTFIX = "-cs-namespace-set";
    public static String GROUP = "SENTINEL_GROUP";

    @Bean
    public ConfigService nacosConfigService(NacosDiscoveryProperties nacosDiscoveryProperties) throws NacosException {
        if (StringUtils.hasLength(nacosDiscoveryProperties.getGroup())) GROUP = nacosDiscoveryProperties.getGroup();
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.USERNAME, nacosDiscoveryProperties.getUsername());
        properties.put(PropertyKeyConst.PASSWORD, nacosDiscoveryProperties.getPassword());
        properties.put(PropertyKeyConst.NAMESPACE, nacosDiscoveryProperties.getNamespace());
        properties.put(PropertyKeyConst.SERVER_ADDR, nacosDiscoveryProperties.getServerAddr());
        return ConfigFactory.createConfigService(properties);
    }
}